﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Security.Permissions;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WebControls;
namespace delegate_tasks_manager.Delegation_WebPart
{
    public partial class Delegation_WebPartUserControl : UserControl
    {
        SPWeb web;
        SPQuery query;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (SPContext.Current.FormContext.FormMode != SPControlMode.Display)
            {
                EnableValidators(false);
            }
            else
            {
                EnableValidators(true);
            }
            web = SPContext.Current.Web;
                if (!IsPostBack)
                {
                    get_user();
                }
        }
        void get_user()
        {
            try
            {
                if(web.Lists.TryGetList("Delegation_List")==null)               
                {
                 web.AllowUnsafeUpdates = true;
                 web.Update();
                 web.Lists.Add("Delegation_List", "This is used for Megren Delegation Manager", web.ListTemplates["Custom List"]);
                 SPList newList = web.Lists["Delegation_List"];
                 newList.Fields.Add("task_owner", SPFieldType.User, true);
                 newList.Fields.Add("Delegation Start Time", SPFieldType.DateTime, true);
                 newList.Fields.Add("Delegation End Time", SPFieldType.DateTime, true);
                 newList.Fields.Add("Task_List", SPFieldType.Text, true);
                 newList.Update();
                 web.AllowUnsafeUpdates = false;
                 web.Update();
                }
                query = new SPQuery();
                query.ViewFields = "<FieldRef Name='task_owner' /><FieldRef Name='Title' /><FieldRef Name='Delegation_x0020_Start_x0020_Tim' /><FieldRef Name='Delegation_x0020_End_x0020_Time' /><FieldRef Name='Task_List' /><FieldRef Name='ID' />";
                if (web.CurrentUser != null)
                {
                    query.Query = "<Where><Eq><FieldRef Name='task_owner'/><Value Type='Text'>" + web.CurrentUser.ToString() + "</Value></Eq></Where>";
                }
                else
                {
                    query.Query = "<Where><Eq><FieldRef Name='task_owner'/>?<Value Type='Text'></Value></Eq></Where>";
                }
                if (web.Lists["Delegation_List"].GetItems(query).Count != 0)
                {
                    SPItem item = web.Lists["Delegation_List"].GetItems(query)[0];
                    this.RadioButtonList1.Items.Add(item["Task_List"].ToString());
                    this.RadioButtonList1.Items[0].Selected = true;
                    this.DateTimeControl1.SelectedDate = Convert.ToDateTime(item["Delegation Start Time"].ToString());
                    this.DateTimeControl2.SelectedDate = Convert.ToDateTime(item["Delegation End Time"].ToString());
                    this.peopleEditor.CommaSeparatedAccounts = item["Title"].ToString();
                    this.Role_ID_Label.Text = item["ID"].ToString() + "-" + web.CurrentUser.Name;
                    this.peopleEditor.Validate();
                    this.Button3.Visible = true;
                    this.RadioButtonList1.Enabled = false;
                    this.DateTimeControl1.Enabled =false;
                    this.DateTimeControl2.Enabled = false;
                    peopleEditor.Enabled =false;
                    this.Button1.Visible = false;
                    validate_dates();
                }
                else
                {
                    this.Button1.Visible = true;
                    this.Button3.Visible = false;
                    this.Delegation_Status_Image.ImageUrl = "/_layouts/images/KPIDefault-1.GIF";
                    this.RadioButtonList1.Items.Clear();
                    this.Notification_Label.Text = "You don't have Delegation role set.";
                    SPListCollection tasks_lists = web.Lists;
                    foreach (SPList TaskList in tasks_lists)
                    {
                        if (TaskList.ContentTypes[0].Name == "Task")
                        {
                            this.RadioButtonList1.Items.Add(TaskList.Title);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Notification_Label.Text = ex.Message;
            }    
        }
        bool validate_dates() 
        {
            if (this.DateTimeControl1.SelectedDate >= this.DateTimeControl2.SelectedDate)
            {
                this.Notification_Label.Text = "'End' date should be greater than 'Start'";
                this.Delegation_Status_Image.ImageUrl = "/_layouts/images/KPIDefault-2.GIF";
                return false ;
            }
            else if (this.DateTimeControl2.SelectedDate < DateTime.Now)
            {
                this.Notification_Label.Text = "Delegation Role Expired!!";
                this.Delegation_Status_Image.ImageUrl = "/_layouts/images/KPIDefault-1.GIF";
                return false;
            }
            else
            {
                this.Notification_Label.Text = "Delegation Role Valid";
                this.Delegation_Status_Image.ImageUrl = "/_layouts/images/KPIDefault-0.GIF";
                return true ;
            }

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!validate_dates())
            {
                return;
            }
            if (this.DateTimeControl1.SelectedDate >= this.DateTimeControl2.SelectedDate)
            {
                this.Notification_Label.Text = "'End' date should be greater than 'Start'";
                this.Delegation_Status_Image.ImageUrl = "/_layouts/images/KPIDefault-2.GIF";
                return;
            }
                if (this.peopleEditor.Accounts.Count > 0)
                {
                    if (web.CurrentUser != null)
                    {
                        try
                        {
                            SPList list = web.Lists[RadioButtonList1.SelectedItem.Text.ToString()];
                            AddEventReceiver(list, "delegation", "delegate_tasks_manager.Delegation_WebPart.event_Class", SPEventReceiverType.ItemAdding);
                            additem_delegate(this.peopleEditor.Accounts[0].ToString(), web.CurrentUser, RadioButtonList1.SelectedValue.ToString(), this.DateTimeControl1.SelectedDate, this.DateTimeControl2.SelectedDate);
                            this.Notification_Label.Text = "Role has been applied successful on task list named " + RadioButtonList1.SelectedItem.Text.ToString();
                            clear_data();
                            get_user();
                        }
                        catch (Exception ex)
                        {
                            this.Notification_Label.Text = ex.Message;
                        }
                    }
                }
        }
        
        void additem_delegate(string username, SPUser task_owner, string task_list, DateTime task_start, DateTime task_end)
        {
            try
            {
                SPListItem item = web.Lists["Delegation_List"].Items.Add();
                item["Title"] = username;
                item["task_owner"]= task_owner;
                item["Task_List"] = task_list;
                item["Delegation Start Time"] = task_start;
                item["Delegation End Time"] = task_end;
                item.Update();
            }
            catch (Exception ex)
            {
                this.Notification_Label.Text = ex.Message;
            }    
        }
        void clear_data()
        {
            peopleEditor.Enabled = true;
            peopleEditor.ResolvedEntities.Clear();
            peopleEditor.Entities.Clear();

            this.RadioButtonList1.Items.Clear();
            this.RadioButtonList1.Enabled = true;

            this.Button3.Visible = false;
            this.Button1.Visible = true;

            this.DateTimeControl1.ClearSelection();
            this.DateTimeControl1.Enabled = true;

            this.DateTimeControl2.ClearSelection();
            this.DateTimeControl2.Enabled = true;          

            this.Role_ID_Label.Text = "";
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
                try
                {
                    SPList list = web.Lists[RadioButtonList1.SelectedItem.Text.ToString()];
                    web.Lists["Delegation_List"].Items.DeleteItemById(Convert.ToInt32(Role_ID_Label.Text.Remove(Role_ID_Label.Text.LastIndexOf("-"))));
                    clear_data();
                    get_user();
                    this.Notification_Label.Text = "Delegation Role deleted";
                }
                catch (Exception ex)
                {
                    this.Notification_Label.Text = ex.Message;
                }    
        }
        private void AddEventReceiver(SPList list, string name, string className, SPEventReceiverType type)
        {
            if (list.EventReceivers.Count == 0)
            {
                try
                {
                    SPEventReceiverDefinition eventReceiver = list.EventReceivers.Add();
                    eventReceiver.Name = name;
                    eventReceiver.Assembly = System.Reflection.Assembly.GetExecutingAssembly().FullName;
                    eventReceiver.Class = className;
                    eventReceiver.SequenceNumber = 2001;
                    eventReceiver.Type = type;
                    eventReceiver.HostId = list.ID;
                    eventReceiver.HostType = SPEventHostType.List;
                    eventReceiver.Update();
                }
                catch (Exception ex)
                {
                    this.Notification_Label.Text = ex.Message;
                }    
            }
        }
        private void DeleteEventReceivers(SPList list, string className)
        {   
                if (web.CurrentUser != null)
                {
                    try
                    {
                        foreach (SPEventReceiverDefinition eventReceiver in list.EventReceivers)
                        {
                            eventReceiver.Delete();
                            list.Update();
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Notification_Label.Text = ex.Message;
                    }    
                }   
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
          Page.Response.Redirect("/", true);
        }
        public void EnableValidators(bool enableVal)
        {
            RequiredFieldValidator1.Enabled = enableVal;
            peopleEditor.ValidatorEnabled = enableVal;
            DateTimeControl1.IsRequiredField = enableVal;
            DateTimeControl2.IsRequiredField = enableVal;
        }
    }
}
